#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import json
import subprocess

def deal_local_package(download_configs: list) -> None:
    remain_configs = []
    
    current_file_dir = os.path.dirname(os.path.abspath(__file__))
    config_file_path = os.path.join(current_file_dir, "local_package.json")
    with open(config_file_path, "r", encoding="utf-8") as f:
        local_package_configs = json.load(f)
    
    for config_item in download_configs:
        is_in_local, local_path = is_in_local_package(
            local_package_configs, config_item
        )
        if is_in_local:
            print("Using local package for {}".format(config_item.get("remote_url")))
            clean_destination(config_item)
            extract_compress_files(local_path, config_item.get("unzip_dir"))
        else:
            remain_configs.append(config_item)
    return remain_configs

def clean_destination(config_item):
    unzip_dir = config_item.get("unzip_dir")
    unzip_filename = config_item.get("unzip_filename")
    dest_path = os.path.join(unzip_dir, unzip_filename)
    if os.path.exists(dest_path):
        run_cmd(["rm", "-rf", '{}/{}'.format(unzip_dir, unzip_filename)])

def is_in_local_package(local_package_configs, config_item) -> tuple:
    current_file_dir = os.path.dirname(os.path.abspath(__file__))
    unzip_dir = config_item.get("unzip_dir")
    unzip_filename = config_item.get("unzip_filename")
    name = config_item.get("name")
    for local_package in local_package_configs:
        if (
            local_package.get("name") == name
            and unzip_dir.endswith(local_package.get("unzip_dir"))
            and local_package.get("unzip_filename") == unzip_filename
        ):
            local_file = os.path.join(current_file_dir, "packages", local_package.get("local_file"))
            if os.path.exists(local_file):
                return True, local_file
            else:
                print("Local package {} not exists".format(local_file))
    return False, None


def extract_compress_files(source_file: str, unzip_dir: str):
    """
    解压缩文件
    """
    if not os.path.exists(unzip_dir):
        os.makedirs(unzip_dir, exist_ok=True)
    if source_file.endswith(".zip"):
        command = ["unzip", "-qq", "-o", "-d", unzip_dir, source_file]
    elif source_file.endswith(".tar.gz"):
        command = ["tar", "-xzf", source_file, "-C", unzip_dir]
    elif source_file.endswith(".tar.xz"):
        command = ["tar", "-xJf", source_file, "-C", unzip_dir]
    elif source_file.endswith(".tar"):
        command = ["tar", "-xvf", source_file, "-C", unzip_dir]
    else:
        print("暂不支持解压此类型压缩文件！")
        return
    
    _, err, retcode = run_cmd(command)
    if retcode != 0:
        print("解压失败，错误信息：", err)
        return
    
def run_cmd(cmd: list) -> tuple:
    res = subprocess.Popen(
        cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    sout, serr = res.communicate()
    return sout.rstrip().decode("utf-8"), serr, res.returncode